Selection Statements
Selection statements allow you to control the flow of program execution based on conditions. They enable decision-making in your programs.
1. if Statement
The simplest form of selection statement that executes a block of code only if a condition is true.
// Syntax
if (condition) {
// Code to execute if condition is true
}
// Example
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote!");
}
2. if-else Statement
Provides an alternative block of code to execute when the condition is false.
// Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
// Example
int score = 75;
if (score >= 60) {
System.out.println("You passed!");
} else {
System.out.println("You failed!");
}
3. if-else-if Ladder
Used to test multiple conditions in sequence. The first condition that evaluates to true is executed.
// Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if all conditions are false
}
// Example: Grade calculation
int marks = 85;
char grade;
if (marks >= 90) {
grade = 'A';
} else if (marks >= 80) {
grade = 'B';
} else if (marks >= 70) {
grade = 'C';
} else if (marks >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade: " + grade);
4. Nested if Statements
if statements can be nested inside other if statements to create complex decision trees.
// Example: Scholarship eligibility
int age = 20;
double gpa = 3.8;
boolean hasExtracurricular = true;
if (age >= 18 && age <= 25) {
if (gpa >= 3.5) {
if (hasExtracurricular) {
System.out.println("Eligible for Full Scholarship!");
} else {
System.out.println("Eligible for Partial Scholarship");
}
} else {
System.out.println("GPA too low for scholarship");
}
} else {
System.out.println("Age not eligible for scholarship");
}
5. switch Statement
A multi-way branch statement that provides an alternative to long if-else-if ladders. It's cleaner and more efficient when comparing against constant values.
Basic switch Syntax
// Syntax
switch (expression) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
// More cases...
default:
// Code to execute if no case matches
break;
}
// Example: Day of the week
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day: " + dayName);
Advanced switch Features (Java 7+)
// String switch (Java 7+)
String grade = "B";
String message;
switch (grade) {
case "A":
message = "Excellent!";
break;
case "B":
message = "Good!";
break;
case "C":
message = "Average";
break;
case "D":
message = "Below Average";
break;
case "F":
message = "Fail";
break;
default:
message = "Invalid grade";
break;
}
// Multiple case labels
int month = 7;
String season;
switch (month) {
case 12: case 1: case 2:
season = "Winter";
break;
case 3: case 4: case 5:
season = "Spring";
break;
case 6: case 7: case 8:
season = "Summer";
break;
case 9: case 10: case 11:
season = "Fall";
break;
default:
season = "Invalid month";
break;
}
Iteration Statements (Loops)
Iteration statements allow you to execute a block of code repeatedly based on a condition. They are essential for processing collections of data and performing repetitive tasks.
1. while Loop
Executes a block of code as long as the condition remains true. The condition is checked before each iteration.
// Syntax
while (condition) {
// Code to execute while condition is true
// Update loop control variable
}
// Example: Print numbers 1 to 5
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++; // Important: Update control variable
}
// Example: Sum of first 10 natural numbers
int sum = 0;
int num = 1;
while (num <= 10) {
sum += num;
num++;
}
System.out.println("Sum: " + sum);
2. do-while Loop
Similar to while loop, but the condition is checked after each iteration. This guarantees at least one execution of the loop body.
// Syntax
do {
// Code to execute
// Update loop control variable
} while (condition);
// Example: Menu-driven program
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\n=== Menu ===");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Addition operation");
break;
case 2:
System.out.println("Subtraction operation");
break;
case 3:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 3);
scanner.close();
3. for Loop
A compact loop that combines initialization, condition, and increment in a single line. Ideal when you know the number of iterations in advance.
// Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}
// Example: Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
// Example: Calculate factorial
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial of " + n + " is " + factorial);
// Example: Reverse a string
String str = "Hello";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed: " + reversed);
4. Enhanced for Loop (for-each)
Simplified loop for iterating over arrays and collections. Introduced in Java 5.
// Syntax
for (dataType variable : array/collection) {
// Code to execute
}
// Example: Iterate over array
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println("Number: " + num);
}
// Example: Iterate over string array
String[] fruits = {"Apple", "Banana", "Orange", "Grape"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
// Example: Calculate sum of array elements
double[] prices = {10.5, 20.0, 15.75, 30.25};
double total = 0;
for (double price : prices) {
total += price;
}
System.out.println("Total: $" + total);
5. Nested Loops
Loops can be nested inside other loops to create complex patterns and process multi-dimensional data.
// Example: Multiplication table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
// Example: Pattern printing
for (int i = 1; i <= 5; i++) {
// Print spaces
for (int j = 1; j <= 5 - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
// Example: 2D array processing
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Jump Statements
Jump statements allow you to transfer control to another part of the program. They provide additional control over loop execution and program flow.
1. break Statement
Immediately terminates the loop or switch statement and transfers control to the statement immediately following it.
// Example: Break out of loop when condition is met
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break; // Exit the loop
}
System.out.println("Number: " + i);
}
// Output: 1, 2, 3, 4, 5
// Example: Search for element in array
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;
boolean found = false;
for (int num : numbers) {
if (num == target) {
found = true;
break; // Exit loop when found
}
}
if (found) {
System.out.println("Target found!");
} else {
System.out.println("Target not found!");
}
2. continue Statement
Skips the current iteration of the loop and continues with the next iteration.
// Example: Skip even numbers
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Odd number: " + i);
}
// Output: 1, 3, 5, 7, 9
// Example: Sum of positive numbers only
int[] numbers = {10, -5, 20, -15, 30, -25};
int sum = 0;
for (int num : numbers) {
if (num < 0) {
continue; // Skip negative numbers
}
sum += num;
}
System.out.println("Sum of positive numbers: " + sum);
3. return Statement
Exits from the current method and returns control to the calling method. Can also return a value.
// Example: Return from method
public boolean isEven(int number) {
if (number % 2 == 0) {
return true; // Exit method and return true
}
return false; // Exit method and return false
}
// Example: Return value from method
public int findMax(int[] array) {
if (array.length == 0) {
return -1; // Return error code
}
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max; // Return the maximum value
}
4. Labeled break and continue
Java allows labeling loops to break or continue from nested loops.
// Example: Labeled break
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i=" + i + ", j=" + j);
if (i == 2 && j == 2) {
break outerLoop; // Exit both loops
}
}
}
// Example: Labeled continue
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
continue outerLoop; // Skip to next iteration of outer loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
Practical Examples
Example 1: Number Guessing Game
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int secretNumber = random.nextInt(100) + 1; // 1-100
int guess;
int attempts = 0;
boolean hasWon = false;
System.out.println("=== Number Guessing Game ===");
System.out.println("Guess a number between 1 and 100");
while (attempts < 10) {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
attempts++;
if (guess == secretNumber) {
hasWon = true;
break;
} else if (guess < secretNumber) {
System.out.println("Too low! Try again.");
} else {
System.out.println("Too high! Try again.");
}
System.out.println("Attempts remaining: " + (10 - attempts));
}
if (hasWon) {
System.out.println("Congratulations! You won in " + attempts + " attempts!");
} else {
System.out.println("Game Over! The number was: " + secretNumber);
}
scanner.close();
}
}
Example 2: ATM Menu System
import java.util.Scanner;
public class ATMSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double balance = 1000.0;
int choice;
do {
System.out.println("\n=== ATM Menu ===");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Current Balance: $" + balance);
break;
case 2:
System.out.print("Enter deposit amount: $");
double deposit = scanner.nextDouble();
if (deposit > 0) {
balance += deposit;
System.out.println("Deposit successful! New balance: $" + balance);
} else {
System.out.println("Invalid amount!");
}
break;
case 3:
System.out.print("Enter withdrawal amount: $");
double withdraw = scanner.nextDouble();
if (withdraw > 0 && withdraw <= balance) {
balance -= withdraw;
System.out.println("Withdrawal successful! New balance: $" + balance);
} else if (withdraw > balance) {
System.out.println("Insufficient funds!");
} else {
System.out.println("Invalid amount!");
}
break;
case 4:
System.out.println("Thank you for using ATM!");
break;
default:
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 4);
scanner.close();
}
}
Example 3: Student Grade Management
import java.util.Scanner;
public class GradeManagement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numStudents = scanner.nextInt();
String[] names = new String[numStudents];
int[] marks = new int[numStudents];
char[] grades = new char[numStudents];
// Input student data
for (int i = 0; i < numStudents; i++) {
scanner.nextLine(); // Clear buffer
System.out.print("Enter name of student " + (i + 1) + ": ");
names[i] = scanner.nextLine();
System.out.print("Enter marks for " + names[i] + ": ");
marks[i] = scanner.nextInt();
// Calculate grade
if (marks[i] >= 90) {
grades[i] = 'A';
} else if (marks[i] >= 80) {
grades[i] = 'B';
} else if (marks[i] >= 70) {
grades[i] = 'C';
} else if (marks[i] >= 60) {
grades[i] = 'D';
} else {
grades[i] = 'F';
}
}
// Display results
System.out.println("\n=== Student Results ===");
System.out.println("Name\t\tMarks\tGrade\tStatus");
System.out.println("----------------------------------------");
int totalMarks = 0;
int passedCount = 0;
for (int i = 0; i < numStudents; i++) {
String status = (grades[i] != 'F') ? "Passed" : "Failed";
System.out.println(names[i] + "\t\t" + marks[i] + "\t" + grades[i] + "\t" + status);
totalMarks += marks[i];
if (grades[i] != 'F') {
passedCount++;
}
}
// Calculate statistics
double average = (double) totalMarks / numStudents;
double passPercentage = (double) passedCount / numStudents * 100;
System.out.println("\n=== Class Statistics ===");
System.out.println("Total Students: " + numStudents);
System.out.println("Average Marks: " + String.format("%.2f", average));
System.out.println("Pass Percentage: " + String.format("%.2f", passPercentage) + "%");
scanner.close();
}
}
Example 4: Pattern Printing
public class PatternPrinting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
// Right triangle pattern
System.out.println("\n=== Right Triangle ===");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Inverted right triangle
System.out.println("\n=== Inverted Right Triangle ===");
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pyramid pattern
System.out.println("\n=== Pyramid ===");
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
// Number pattern
System.out.println("\n=== Number Pattern ===");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
scanner.close();
}
}
Best Practices and Guidelines
1. Choosing the Right Control Structure
| Scenario | Recommended Control Structure | Reason |
|---|---|---|
| Simple true/false condition | if-else | Clear and readable for binary decisions |
| Multiple constant values | switch | Cleaner and more efficient than long if-else chains |
| Known number of iterations | for loop | Compact initialization, condition, and increment |
| Unknown iterations, condition-based | while loop | Flexible for condition-based iteration |
| At least one iteration needed | do-while loop | Guarantees first iteration execution |
| Iterating over collections | enhanced for loop | Simplified syntax, no index management |
2. Loop Optimization Techniques
// Good: Cache array length
int[] array = {1, 2, 3, 4, 5};
int length = array.length; // Cache length
for (int i = 0; i < length; i++) {
// Process array[i]
}
// Avoid: Calling methods repeatedly in loop condition
// Bad: for (int i = 0; i < array.length; i++)
// Good: Use appropriate loop type
for (String item : stringArray) {
// Simple iteration
}
// Good: Minimize operations inside loop
for (int i = 0; i < 1000; i++) {
// Keep loop body minimal
result += i; // Simple operation
}
3. Common Pitfalls and Solutions
Infinite Loops
// Problem: Infinite loop
int i = 0;
while (i < 10) {
System.out.println(i);
// Forgot to increment i!
}
// Solution: Always update loop control variable
int i = 0;
while (i < 10) {
System.out.println(i);
i++; // Increment control variable
}
Off-by-One Errors
// Problem: Off-by-one error
int[] array = new int[10];
for (int i = 0; i <= array.length; i++) { // Should be <
array[i] = i; // ArrayIndexOutOfBoundsException at i = 10
}
// Solution: Correct loop bounds
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
Missing break in switch
// Problem: Missing break causes fall-through
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
// Missing break!
case 2:
System.out.println("Tuesday");
break;
}
// Output: Monday Tuesday (unexpected!)
// Solution: Always include break
switch (day) {
case 1:
System.out.println("Monday");
break; // Add break
case 2:
System.out.println("Tuesday");
break;
}
4. Code Readability Guidelines
- Use meaningful variable names for loop counters and conditions
- Keep loops short and focused on a single task
- Avoid deep nesting (more than 3 levels) when possible
- Use early returns to reduce nesting in methods
- Extract complex conditions to well-named boolean variables
- Comment complex logic especially in nested structures
// Good: Clear and readable
boolean isEligibleForDiscount = (age >= 18) && (hasMembership || isStudent);
if (isEligibleForDiscount) {
applyDiscount();
}
// Good: Early return to reduce nesting
public void processOrder(Order order) {
if (order == null) {
return; // Early return
}
if (!order.isValid()) {
return; // Early return
}
// Main logic here
processValidOrder(order);
}
Summary
Key Points Covered:
- Selection Statements: if, if-else, if-else-if, nested if, switch
- Iteration Statements: while, do-while, for, enhanced for, nested loops
- Jump Statements: break, continue, return, labeled statements
- Practical Applications: Games, menu systems, data processing, patterns
- Best Practices: Choosing right structures, optimization, avoiding pitfalls